package com.mediacloud.app.newsmodule.fragment.baoliao.frag;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.baoyz.actionsheet.ActionSheet;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.mediacloud.app.newsmodule.model.baoliao.list.list.BaoNiaoListItem;
import com.mediacloud.app.model.eventbus.event.LoginEvent;
import com.mediacloud.app.model.interfaces.DataInvokeCallBack;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.model.news.ArticleListData;
import com.mediacloud.app.model.utils.ViewUtils;
import com.mediacloud.app.model.view.floatwin.FloatButtonGroup;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.activity.microlive.BaseRecyclerAdapter;
import com.mediacloud.app.newsmodule.activity.microlive.BaseRecyclerAdapterX;
import com.mediacloud.app.newsmodule.fragment.SimpleBottomSheetDialog;
import com.mediacloud.app.newsmodule.fragment.baoliao.activity.BaoLiaoDetailActivity;
import com.mediacloud.app.newsmodule.fragment.baoliao.adapter.BaoLiaoRankListAdapter;
import com.mediacloud.app.newsmodule.fragment.nav2.BaseRecyclerListFragment;
import com.mediacloud.app.newsmodule.utils.BaoLiaoBlockListUtils;
import com.mediacloud.app.newsmodule.utils.BaoLiaoItemMoreHandler;
import com.mediacloud.app.newsmodule.utils.CacheDataKt;
import com.mediacloud.app.newsmodule.utils.NewsItemClickUtils;
import com.mediacloud.app.newsmodule.utils.NewsListDataInvoker;
import com.zimeiti.fragment.ZiMeiTiAttentionDivider;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 爆料排行列表
 */

public class BaoLiaoRankListFragment extends BaseRecyclerListFragment<BaoLiaoRankListAdapter>
        implements DataInvokeCallBack<ArticleListData>
        , BaseRecyclerAdapterX.ItemClickListener, SimpleBottomSheetDialog.ItemClickListener {

    protected NewsListDataInvoker newsListDataInvoker;

    @Override
    public BaoLiaoRankListAdapter getRecyclerAdapter() {
        return new BaoLiaoRankListAdapter(getActivity());
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        newsListDataInvoker = new NewsListDataInvoker(this);
        refreshLayout.autoRefresh(200);
//        recyclerView.setPadding(10, 0, 10, 0);
//        recyclerAdapter.itemClickListener = this;
//        recyclerAdapter.actionSheetListener = this;
//        recyclerAdapter.simpleBtmItemClickListener = this;
        recyclerView.addItemDecoration(new ZiMeiTiAttentionDivider(view.getResources().getDimensionPixelOffset(R.dimen.dimen5), 0xFFEEEEEE, view.getResources().getDimensionPixelOffset(R.dimen.dimen5)));
        //尝试修滑动的时候抖动问题
//        recyclerView.setRecycledViewPool(new RecyclerView.RecycledViewPool(){
//            @Nullable
//            @Override
//            public RecyclerView.ViewHolder getRecycledView(int viewType) {
//                return super.getRecycledView(viewType);
//            }
//
//            @Override
//            public void putRecycledView(RecyclerView.ViewHolder scrap) {
//                try {
//                    if(scrap instanceof BaoLiaoNavListPureTxtHolder){
//                        View v = scrap.itemView.findViewById(R.id.baoniaogrid);
//                        ViewGroup.LayoutParams layoutParams = v.getLayoutParams();
//                        layoutParams.height = v.getHeight();
//                        v.setLayoutParams(layoutParams);
//                        ViewGroup.LayoutParams params = scrap.itemView.getLayoutParams();
//                        params.height = scrap.itemView.getHeight();
//                        scrap.itemView.setLayoutParams(params);
//                    }
//                }catch (Exception e){
//
//                }
//                super.putRecycledView(scrap);
//            }
//        });
        if(retryTips!=null){
            retryTips.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!currentState.equals(TYPE_LOADING)) {
                        showStateView(TYPE_LOADING, false);
                        pageIndex = 1;
                        newsListDataInvoker.getRankList(pageIndex, perPageSize);
                    }
                }
            });
        }
    }


    @Override
    public RecyclerView.LayoutManager getLayoutManager() {
        return ViewUtils.generateRecyclerLinearLayoutManager(getActivity(), true);
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        pageIndex++;
        newsListDataInvoker.getRankList(pageIndex, perPageSize);
    }

    @Override
    public void onDestroy() {
        if (newsListDataInvoker != null)
            newsListDataInvoker.destory();
        super.onDestroy();
    }

    @Override
    public void onDetach() {
        super.onDetach();
        if (newsListDataInvoker != null)
            newsListDataInvoker.destory();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        //先讀取緩存，是否考慮取消
        ArticleListData dataResult = CacheDataKt.readData(this, "baoliaoRank", ArticleListData.class);
        if (recyclerAdapter != null && recyclerAdapter.getItemCount() == 0 && dataResult != null && dataResult.articleList.size() > 0) {
            success(dataResult);
        }
        pageIndex = 1;
        newsListDataInvoker.getRankList(pageIndex, perPageSize);
    }

    @Override
    public void success(ArticleListData data) {
        if (pageIndex == 1) {
            refreshLayout.finishRefresh();
            //沒有catlogID,所以key值自定义了
            CacheDataKt.saveData(this, "baoliaoRank", data.orginData + "");
        }
        if (!data.more)
            refreshLayout.finishLoadMoreWithNoMoreData();
        else
            refreshLayout.finishLoadMore();
        JSONObject result = data.orginData.optJSONObject("data");
        if(pageIndex==1){
            if (FloatButtonGroup.haveFloatField(result)) {
                initFloatWin(result);
            } else {
                hideFloatWin();
            }
        }
        if (pageIndex == 1) {
            recyclerAdapter.getData().clear();
            //组件必须
            try {
                addComponent(data.componentItems);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
//        Set<String> blockList = BaoLiaoBlockListUtils.getUserBlockedList(getActivity());
        //被屏蔽人列表
//        Set<String> blockPeopleList = BaoLiaoBlockListUtils.getUserBlockedPeopleList(getActivity());
        for (ArticleItem articleItem : data.articleList) {
            if (articleItem.orginDataObject != null) {
                try {
                    BaoNiaoListItem item = JSON.parseObject(articleItem.orginDataObject + "", BaoNiaoListItem.class);
                    recyclerAdapter.getData().add(item);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        int size = recyclerAdapter.getItemCount();
        if (pageIndex == 1) {
            recyclerView.notifyDataSetChanged();
        } else {
            recyclerView.notifyItemRangeInserted(size, data.articleList.size());
        }

        if (pageIndex == 1 && recyclerAdapter.getData() != null && recyclerAdapter.getData().size() == 0 && data.componentItems.size() == 0) {
            showStateView(TYPE_NO_CONTENT, false);
        } else
            closeStateView();
        data.articleList.clear();
    }

    @Override
    public void fault(Object data) {
        pageIndex -= 1;
        if (data != null && pageIndex == 0) {
            showStateView(TYPE_NET_NOT_GIVE_FORCE, false);
        } else {
            showStateView(TYPE_NO_CONTENT, false);
        }
    }

    @Override
    public void onItemClick(int index, boolean isFromAdaptor, BaseRecyclerAdapter adapter) {
        if (recyclerAdapter.getItem(index).getIs_display() == 0) {
            Log.w("APPTAG", "审核没过的  不能点");
            return;
        }
        Intent intent = new Intent(getActivity(), BaoLiaoDetailActivity.class);
        intent.putExtra("id", recyclerAdapter.getItem(index).getId());
        intent.putExtra("status", recyclerAdapter.getItem(index).getStatus());
        intent.putExtra("url", recyclerAdapter.getItem(index).getShareHtml());
        NewsItemClickUtils.startActivity(getActivity(), intent);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void loginState(LoginEvent loginEvent) {
        f5();
    }


    @Override
    public void itemClicked(int index, @NotNull Object tagData) {
        switch (index) {
            case 0:
                //屏蔽此人
//                ToastUtil.show(getActivity(), "屏蔽此人");
                if (recyclerAdapter.currentClickMorePosition > -1 && recyclerAdapter.currentClickMorePosition < recyclerAdapter.getItemCount()) {
                    String userId = "" + recyclerAdapter.getData().get(recyclerAdapter.currentClickMorePosition).getUid();
                    BaoLiaoBlockListUtils.addBlockPeople(getActivity(), userId);
                    removeDataByBlockPeople();
                }
                break;
            case 1:
                //不想看这条
                if (recyclerAdapter.currentClickMorePosition > -1 && recyclerAdapter.currentClickMorePosition < recyclerAdapter.getItemCount()) {
                    String id = "" + recyclerAdapter.getData().get(recyclerAdapter.currentClickMorePosition).getId();
                    BaoLiaoBlockListUtils.addUserBlockItem(getActivity(), id);
                    recyclerAdapter.getData().remove(recyclerAdapter.currentClickMorePosition);
                    recyclerView.notifyDataSetChanged();
                }
                break;
            case 2:
                //举报
                BaoLiaoItemMoreHandler.showReportDialog(getContext(), recyclerAdapter.getItem(recyclerAdapter.currentClickMorePosition).getUid(), getChildFragmentManager());
                break;
            default:
                break;
        }
    }

    //移除被屏蔽人的数据
    private void removeDataByBlockPeople() {
        Set<String> blockPeopleList = BaoLiaoBlockListUtils.getUserBlockedPeopleList(getActivity());
        List<BaoNiaoListItem> itemList = new ArrayList<>(recyclerAdapter.getData());
        for (BaoNiaoListItem baoNiaoListItem : itemList) {
            try {
                if (blockPeopleList.contains(baoNiaoListItem.getUid())) {
                    recyclerAdapter.getData().remove(baoNiaoListItem);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        recyclerView.notifyDataSetChanged();
    }
}